package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.YhMember;
import com.ruoyi.common.enums.PointRecordType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.Arith;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.YhDetails;
import com.ruoyi.system.domain.YhMemberLevelRule;
import com.ruoyi.system.domain.YhPointRecord;
import com.ruoyi.system.domain.vo.YhScanCodeRecordVo;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.YhScanCodeRecordMapper;
import com.ruoyi.system.domain.YhScanCodeRecord;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户烟盒扫码记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-06-06
 */
@Service
public class YhScanCodeRecordServiceImpl extends ServiceImpl<YhScanCodeRecordMapper, YhScanCodeRecord> implements IYhScanCodeRecordService
{

    @Autowired
    private YhScanCodeRecordMapper scanCodeRecordMapper;

    @Autowired
    private IYhDetailsService detailsService;

    @Autowired
    private IYhMemberService memberService;

    @Autowired
    private IYhMemberLevelRuleService memberLevelRuleService;

    @Transactional
    @Override
    public boolean ScanCodeRecord(YhScanCodeRecord yhScanCodeRecord) {
        YhMember yhMember = memberService.getById(SecurityUtils.getUserId().toString());
        YhMemberLevelRule memberLevelRule = memberLevelRuleService.getOne(new LambdaQueryWrapper<YhMemberLevelRule>()
                .eq(YhMemberLevelRule::getMemberLevel, yhMember.getMemberLevel()));
        Long allowCount = memberLevelRule.getAllowCount();
        Long count = this.count(new LambdaQueryWrapper<YhScanCodeRecord>()
                .eq(YhScanCodeRecord::getMemberId, yhMember.getId())
                .ge(YhScanCodeRecord::getCreateTime, DateUtils.getDate() + " 00:00:00")
                .le(YhScanCodeRecord::getCreateTime, DateUtils.getDate() + " 23:59:59"));
        if(count > allowCount){
            throw new ServiceException("今日扫码次数已达上线！");
        }

        YhDetails yhDetails = detailsService.getById(yhScanCodeRecord.getYhDetailsId());
        if(StringUtils.isNull(yhDetails) || yhDetails.getState() == 0 || !yhDetails.getBarCode().equals(yhScanCodeRecord.getBarCode())){
            throw new ServiceException("烟盒不存在或暂不回收！");
        }

        if(StringUtils.isNotNull(yhDetails.getAntiFakeCode()) && yhDetails.getAntiFakeCode() == 1) {
            if (StringUtils.isBlank(yhScanCodeRecord.getAntiFakeCode())) {
                throw new ServiceException("请填写防伪码！");
            }
            long antiFakeCodeCount = count(new LambdaQueryWrapper<YhScanCodeRecord>().eq(YhScanCodeRecord::getAntiFakeCode, yhScanCodeRecord.getAntiFakeCode())
                    .eq(YhScanCodeRecord::getYhDetailsId, yhScanCodeRecord.getYhDetailsId()));
            if (antiFakeCodeCount > 0) {
                throw new ServiceException("防伪码已被使用！");
            }
        }
        if(StringUtils.isNotNull(yhDetails.getQrCode()) && yhDetails.getQrCode() == 1) {
            if (StringUtils.isBlank(yhScanCodeRecord.getQrCode())) {
                throw new ServiceException("请扫描二维码！");
            }
            long qrCodeCount = count(new LambdaQueryWrapper<YhScanCodeRecord>().eq(YhScanCodeRecord::getQrCode, yhScanCodeRecord.getQrCode())
                    .eq(YhScanCodeRecord::getYhDetailsId, yhScanCodeRecord.getYhDetailsId()));
            if (qrCodeCount > 0) {
                throw new ServiceException("二维码已被扫描！");
            }
        }

        yhScanCodeRecord.setYhName(yhDetails.getName());
        yhScanCodeRecord.setPoint(yhDetails.getPoint());
        yhScanCodeRecord.setMemberId(SecurityUtils.getUserId().toString());
        yhScanCodeRecord.setState(1);

        return this.save(yhScanCodeRecord);
    }


    @Transactional
    @Override
    public boolean process(YhScanCodeRecord yhScanCodeRecord) {

        YhScanCodeRecord byId = this.getById(yhScanCodeRecord.getId());
        if(byId.getState() != 1){
            throw new ServiceException("当前记录审核状态异常，请刷新页面！");
        }

        Integer state = yhScanCodeRecord.getState();
        // 审核通过
        if(state == 2){
            // 添加用户积分
            YhMember yhMember = memberService.getById(byId.getMemberId());
            // 扫码：SCAN_CODE，提成：COMMISSION
            memberService.addMemberPoint(yhMember.getId(), byId.getPoint(), byId.getId(), PointRecordType.SCAN_CODE.name());


            String parentId = yhMember.getParentId();
            if(StringUtils.isNotEmpty(parentId)) {
                YhMember parentMember = memberService.getById(parentId);
                // 增加上级积分
                if(StringUtils.isNotNull(parentMember)){
                    // 获取当前会员等级积分提成比列
                    YhMemberLevelRule yhMemberLevelRule = memberLevelRuleService.getOne(new LambdaQueryWrapper<YhMemberLevelRule>()
                            .eq(YhMemberLevelRule::getMemberLevel, parentMember.getMemberLevel()));
                    if(StringUtils.isNotNull(yhMemberLevelRule)) {
                        Double pointRate = yhMemberLevelRule.getPointRate();
                        if (pointRate > 0) {
                            Double point = byId.getPoint();
                            double round = Arith.round(Arith.mul(pointRate * 0.01, point), 2);
                            memberService.addMemberPoint(parentMember.getId(), round, byId.getId(), PointRecordType.COMMISSION.name());
                        }
                    }
                }

            }
        }else if(state == 3){
            // 审核未通过
            String remake = yhScanCodeRecord.getRemake();
            if(StringUtils.isEmpty(remake)){
                yhScanCodeRecord.setRemake("审核未通过。");
            }
        }else{
            throw new ServiceException("请求非法！");
        }

        return this.updateById(yhScanCodeRecord);
    }

    @Override
    public List<YhScanCodeRecordVo> listByAdmin(YhScanCodeRecord yhScanCodeRecord) {
        return scanCodeRecordMapper.listByAdmin(yhScanCodeRecord.queryWrapper());
    }

    @Override
    public List<YhScanCodeRecord> listByLoginUser(YhScanCodeRecord yhScanCodeRecord) {
        return scanCodeRecordMapper.listByLoginUser( new QueryWrapper<YhScanCodeRecord>()
                .eq("c.member_id",yhScanCodeRecord.getMemberId())
                .eq(StringUtils.isNotNull(yhScanCodeRecord.getState()),"c.state",yhScanCodeRecord.getState())
                .orderByDesc("c.create_time"));
    }

}
